Skip to main content

Common Matplotlib Methods

📈 Basic Plot Types

  • plt.plot() → line plot
plt.plot(x, y, color='blue', linestyle='--', linewidth=2)
  • plt.scatter() → scatter plot
plt.scatter(x, y, c=colors, s=sizes, alpha=0.7, cmap='viridis')
  • plt.bar() / plt.barh() → vertical / horizontal bar chart
plt.bar(categories, values, color='steelblue')
plt.barh(categories, values, color='coral')
  • plt.hist() → histogram
plt.hist(data, bins=30, edgecolor='black', alpha=0.7)
  • plt.pie() → pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
  • plt.boxplot() → box plot
plt.boxplot(data, labels=['A', 'B', 'C'])
  • plt.fill_between() → fill area between curves
plt.fill_between(x, y1, y2, alpha=0.3)
  • plt.step() → step plot
plt.step(x, y, where='mid')

🎨 Styling & Customization

  • plt.title() → set plot title
plt.title('My Plot', fontsize=14, fontweight='bold')
  • plt.xlabel() / plt.ylabel() → axis labels
plt.xlabel('Time (s)', fontsize=12)
plt.ylabel('Amplitude', fontsize=12)
  • plt.xlim() / plt.ylim() → axis limits
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)
  • plt.xticks() / plt.yticks() → tick locations and labels
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
['0', 'π/2', 'π', '3π/2', '2π'])
  • plt.grid() → toggle grid
plt.grid(True, alpha=0.3, linestyle='--')
  • plt.legend() → show legend
plt.legend(loc='upper right', frameon=True, fontsize=10)
  • plt.colorbar() → add colorbar for colormap plots
plt.colorbar(label='Intensity')
  • plt.axhline() / plt.axvline() → horizontal / vertical reference line
plt.axhline(0, color='gray', linestyle='--')
plt.axvline(np.pi/2, color='red', linestyle=':')

📐 Layout & Subplots

  • plt.subplots() → create figure with grid of subplots
fig, axes = plt.subplots(2, 3, figsize=(12, 8))
  • plt.subplot() → add single subplot to existing figure
plt.subplot(2, 2, 1) # 2x2 grid, position 1
  • plt.tight_layout() → auto-adjust spacing between subplots
plt.tight_layout(pad=2.0)
  • fig.subplots_adjust() → manual subplot spacing
fig.subplots_adjust(wspace=0.3, hspace=0.4)
  • GridSpec → advanced subplot layouts
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(10, 6))
gs = GridSpec(2, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # spans top row
ax2 = fig.add_subplot(gs[1, 0]) # bottom-left
ax3 = fig.add_subplot(gs[1, 1:]) # spans bottom-right

✏️ Text & Annotations

  • plt.text() → add text at data coordinates
plt.text(x, y, 'text', fontsize=12, style='italic')
  • plt.annotate() → add annotation with arrow
plt.annotate('Peak', xy=(x, y), xytext=(x, y + 0.5),
arrowprops=dict(facecolor='black', shrink=0.05))
  • plt.figtext() → add text at figure coordinates
plt.figtext(0.5, 0.02, 'Figure caption', ha='center')
  • Mathematical expressions (LaTeX-style)
plt.title(r'$\sin(x)$ and $\cos(x)$')
plt.xlabel(r'$\theta$ (radians)')

🎯 Axis & Scale

  • plt.xscale() / plt.yscale() → set axis scale
plt.xscale('log')
plt.yscale('symlog')
  • plt.axis() → set axis properties
plt.axis('equal') # equal aspect ratio
plt.axis('tight') # tight bounds
plt.axis('off') # hide axes
plt.axis([0, 10, -1, 1]) # [xmin, xmax, ymin, ymax]
  • plt.twinx() / plt.twiny() → shared x / y axis
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'b-')
ax2.plot(x, y2, 'r-')

💾 Saving & Display

  • plt.savefig() → save figure to file
plt.savefig('figure.png', dpi=300, bbox_inches='tight')
plt.savefig('figure.pdf', bbox_inches='tight')
plt.savefig('figure.svg', bbox_inches='tight')
  • plt.show() → display figure
plt.show()
  • plt.close() → close figure (free memory)
plt.close(fig) # close specific figure
plt.close('all') # close all figures
  • plt.ioff() / plt.ion() → toggle interactive mode
plt.ion() # interactive mode on
plt.ioff() # interactive mode off

🎨 Colormaps

  • plt.get_cmap() → get colormap by name
cmap = plt.get_cmap('viridis')
colors = cmap(np.linspace(0, 1, 10))
  • Available colormaps: 'viridis', 'plasma', 'inferno', 'magma', 'cividis', 'coolwarm', 'RdBu', 'Spectral', 'Greys', 'Blues'
plt.scatter(x, y, c=values, cmap='coolwarm')
plt.colorbar()

📦 Object-Oriented Methods (ax methods)

When using fig, ax = plt.subplots(), use these ax methods:

pyplotax method
plt.plot()ax.plot()
plt.scatter()ax.scatter()
plt.bar()ax.bar()
plt.hist()ax.hist()
plt.title()ax.set_title()
plt.xlabel()ax.set_xlabel()
plt.ylabel()ax.set_ylabel()
plt.xlim()ax.set_xlim()
plt.ylim()ax.set_ylim()
plt.xticks()ax.set_xticks()
plt.grid()ax.grid()
plt.legend()ax.legend()
plt.text()ax.text()
plt.annotate()ax.annotate()